<template>
  <div class="random-fun-container">
    <SplitterGroup direction="horizontal">
      <SplitterPanel :min-size="0" :max-size="40" :default-size="20">
        <div
          class="left-container"
          :style="{
            borderRight: `1px solid ${themeStyle[theme].borderColor1}`
          }"
        >
          <div
            class="title-container"
            :style="{
              background: themeStyle[theme].backgroundColor3
            }"
          >
            <span>列表</span>
          </div>
          <div class="funtion-list-content">
            <div class="funtion-list-item" style="justify-content: center" @click="addRandomFun">
              <PlusOutlined />
            </div>
            <template v-for="(item, index) in randomFunList" :key="index">
              <div class="funtion-list-item" @click="selectRandomFun(item)">
                <div class="icon-content">
                  <span>{{ item.name }}</span>
                </div>
                <div class="remove-icon" @click="removeRandomFun(item.id)">
                  <CloseOutlined />
                </div>
              </div>
            </template>
          </div>
        </div>
      </SplitterPanel>
      <SplitterResizeHandle />
      <SplitterPanel>
        <div class="center-container">
          <div
            class="title-container"
            :style="{
              background: themeStyle[theme].backgroundColor3
            }"
          >
            <span>编辑</span>
          </div>

          <div
            class="name-container"
            :style="{
              borderBottom: `1px solid ${themeStyle[theme].borderColor1}`
            }"
          >
            <span>名称</span>
            <Input
              v-if="randomFunEdit"
              v-model:value="randomFunEdit.name"
              size="small"
              placeholder="请输入名称"
            />
          </div>

          <div
            class="code-title"
            :style="{
              background: themeStyle[theme].backgroundColor3
            }"
          >
            <span>随机函数代码</span>
          </div>

          <div ref="randomFunEditorRef" class="code-editor"></div>
          <div class="operate-btn">
            <Button type="primary" ghost size="small" @click="submitCode">提交</Button>
            <Button type="primary" ghost size="small" @click="testCode">测试</Button>
          </div>
        </div>
      </SplitterPanel>
      <SplitterResizeHandle />
      <SplitterPanel :min-size="0" :max-size="40" :default-size="20">
        <div
          class="right-container"
          :style="{
            borderLeft: `1px solid ${themeStyle[theme].borderColor1}`
          }"
        >
          <div
            class="title-container"
            :style="{
              background: themeStyle[theme].backgroundColor3
            }"
          >
            <span>运行结果</span>
          </div>

          <div class="result-container">
            <template v-for="(item, index) in runResultList" :key="index">
              <div class="result-item">
                <span style="color: #999">【{{ item.time }}】</span>
                <span style="text-wrap: break-word; word-break: break-all">{{ item.result }}</span>
              </div>
            </template>
          </div>
        </div>
      </SplitterPanel>
    </SplitterGroup>
  </div>
</template>

<script setup lang="ts">
import { useStyleStore } from '@renderer/store/globalStyle/style'
import { storeToRefs } from 'pinia'
import { SplitterGroup, SplitterPanel, SplitterResizeHandle } from 'reka-ui'
import { PlusOutlined, CloseOutlined } from '@ant-design/icons-vue'
import { Input, Button } from 'ant-design-vue'
import { onMounted, ref } from 'vue'
import { generateUUID } from '@renderer/utils/utils'
import * as monaco from 'monaco-editor'
import * as ts from 'typescript'
import dayjs from 'dayjs'

// const a = Number((Math.random() * 100).toFixed(2))
// return a

const globalStyleStore = useStyleStore()
const { theme, themeStyle, codeEditorStyle } = storeToRefs(globalStyleStore)

type IRandomFun = {
  id: string
  name: string
  funtionCode: string
  action: () => number
}

// 随机函数列表
const randomFunList = ref<IRandomFun[]>([])

const randomFunEdit = ref<IRandomFun>()

const addRandomFun = () => {
  randomFunEdit.value = {
    id: generateUUID(),
    name: '自定义随机函数',
    funtionCode: '',
    action: () => 0
  }
  editor?.setValue('')
}

//选择某个随机函数
const selectRandomFun = (item: IRandomFun) => {
  randomFunEdit.value = item
  editor?.setValue(item.funtionCode)
}

// 编辑器引用
const randomFunEditorRef = ref<HTMLDivElement | null>(null)
let editor: monaco.editor.IStandaloneCodeEditor | null = null

onMounted(async () => {
  randomFunList.value = await window.electron.ipcRenderer.invoke(
    'randomFun',
    'getRandomFunList',
    []
  )

  if (!randomFunEditorRef.value) return
  // 定义深色主题
  monaco.editor.defineTheme('my-dark-theme', {
    base: 'vs-dark',
    inherit: true,
    rules: codeEditorStyle.value.rules,
    colors: codeEditorStyle.value.colors
  })
  editor = monaco.editor.create(randomFunEditorRef.value, {
    value: '',
    language: 'typescript',
    theme: 'my-dark-theme',
    automaticLayout: true,
    codeLens: true, // 代码透镜
    folding: true, // 代码折叠
    snippetSuggestions: 'inline', // 代码提示
    tabCompletion: 'on', // 代码提示按tab完成
    foldingStrategy: 'auto', // 折叠策略
    smoothScrolling: true // 滚动动画
  })
})
//运行结果列表
const runResultList = ref<{ time: string; result: any }[]>([])

// 执行用户代码
const testCode = async () => {
  if (!editor) return
  const tsCode = editor.getValue()
  const jsCodeStr = ts.transpile(tsCode, { target: ts.ScriptTarget.ES2015 })
  try {
    // 封装成函数并执行（函数内部代码可以有 return）
    const runnable = new Function(jsCodeStr) // 相当于 () => { jsCode }
    const result = runnable()
    console.log('执行结果:', result)

    runResultList.value.push({ time: dayjs().format('HH:mm:ss'), result })
  } catch (err) {
    console.error('执行出错:', err)
  }
}

//代码提交
const submitCode = async () => {
  if (randomFunEdit.value?.id && randomFunEdit.value.name && editor) {
    //获取代码
    const tsCode = editor.getValue()
    const jsCodeStr = ts.transpile(tsCode, { target: ts.ScriptTarget.ES2015 })
    //保存代码
    randomFunEdit.value.funtionCode = jsCodeStr

    //根据id查看中间层是否有这个函数
    const res = await window.electron.ipcRenderer.invoke('randomFun', 'getRandomFunById', [
      randomFunEdit.value.id
    ])
    if (res) {
      const removeItem = JSON.parse(JSON.stringify(res))
      await window.electron.ipcRenderer.invoke('randomFun', 'removeRandomFun', [removeItem])
    }
    const temp = JSON.parse(JSON.stringify(randomFunEdit.value))

    await window.electron.ipcRenderer.invoke('randomFun', 'addRandomFun', [temp])

    randomFunList.value = await window.electron.ipcRenderer.invoke(
      'randomFun',
      'getRandomFunList',
      []
    )
  }
}

const removeRandomFun = async (id: string) => {
  const res = await window.electron.ipcRenderer.invoke('randomFun', 'getRandomFunById', [id])

  if (res) {
    await window.electron.ipcRenderer.invoke('randomFun', 'removeRandomFun', [res])
  }

  randomFunList.value = await window.electron.ipcRenderer.invoke(
    'randomFun',
    'getRandomFunList',
    []
  )
}
</script>

<style scoped lang="scss">
.random-fun-container {
  padding: 5px;
  height: calc(100% - 40px);
  font-size: $font-size-medium;

  .title-container {
    height: 25px;
    display: flex;
    justify-content: left;
    align-items: center;
    padding-left: 10px;
  }

  .left-container {
    height: 100%;
    width: calc(100% - 2px);

    .funtion-list-content {
      height: calc(100% - 25px);
      overflow: auto;
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: center;
      /* 设置滚动条样式 */
      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #ccccccaa;
        border-radius: 4px;
      }

      &::-webkit-scrollbar-thumb:hover {
        background-color: #aaaaaaaa;
      }

      .funtion-list-item {
        margin-top: 5px;
        height: 30px;
        width: calc(100% - 40px);
        background-color: #f1f1f1aa;
        cursor: pointer;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0px 5px;
        position: relative;
        &:hover {
          background-color: #ebf9ffaa;
          .remove-icon {
            display: flex;
          }
        }

        .remove-icon {
          display: none;
          position: absolute;
          top: 0px;
          right: 0px;
          width: 30px;
          height: 30px;
          color: #ff6262;
          justify-content: center;
          align-items: center;
          background-color: #f1f1f1aa;
        }
      }
    }
  }

  .center-container {
    height: 100%;

    .name-container {
      height: 50px;
      display: flex;
      align-items: center;
      justify-content: left;
      padding: 0px 10px;
      gap: 10px;
      span {
        text-wrap: nowrap;
      }
    }

    .code-title {
      height: 25px;
      display: flex;
      justify-content: left;
      align-items: center;
      padding-left: 10px;
    }

    .code-editor {
      height: calc(100% - 145px);
    }
    .operate-btn {
      display: flex;
      justify-content: space-between;
      padding: 0px 10px;
      margin-top: 10px;
    }
  }

  .right-container {
    height: 100%;
    width: calc(100% - 2px);

    .result-container {
      height: calc(100% - 25px);
      width: 100%;
      overflow: auto;
      /* 设置滚动条样式 */
      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-thumb {
        background-color: #ccccccaa;
        border-radius: 4px;
      }

      &::-webkit-scrollbar-thumb:hover {
        background-color: #aaaaaaaa;
      }

      .result-item {
        display: flex;
        justify-content: left;
        align-items: start;
        gap: 10px;
        width: 100%;
        margin-top: 10px;

        span {
          text-wrap: wrap;
        }
      }
    }
  }
}
</style>
